package com.zq.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.product.dao.entity.Brand;
import com.zq.product.mapper.BrandMapper;
import com.zq.product.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 分类品牌 服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2025-05-26
 */
@Service
@Slf4j
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    //    根据条件分页查询品牌
    @Override
    public PageInfo<Brand> findByPage(Integer page, Integer limit, String brandName) {

        PageHelper.startPage(page, limit);
        List<Brand> brandList = this.list(new LambdaQueryWrapper<Brand>()
                .like(StringUtils.hasText(brandName), Brand::getName, brandName).
                orderByAsc(Brand::getId));
        PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
        log.info("查询成功"+pageInfo.getTotal());
        return pageInfo;

    }

    //    保存品牌
    @Override
    public void saveBrand(Brand brand) {
        Brand one = this.getOne(new LambdaQueryWrapper<Brand>().
                eq(StringUtils.hasText(brand.getName()), Brand::getName, brand.getName()));
        if (one != null) {
            throw new RuntimeException("品牌名称已存在");
        }
        this.save(brand);
    }

    //    根据id修改品牌
    @Override
    public void updateByIdApi(Brand brand) {

        Brand byId = this.getById(brand.getId());

//        品牌名称不能重复
//       1、没有修改名称
        if (byId.getName().equals(brand.getName())) {
this.updateById(brand);
        }
//          2、  修改了名称
        else {

            Brand one = this.getOne(new LambdaQueryWrapper<Brand>().eq(Brand::getName, brand.getName()));
//            3、与数据库中的名称重复
            if (one != null) {
                throw new RuntimeException("品牌名称已存在");
            }
            this.updateById(brand);
        }


    }

    //    根据id删除品牌
    @Override
    public void deleteById(Long id) {
        this.removeById(id);

    }

}